package com.dferreira.axil.controller.converter;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.component.UISelectItems;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import com.dferreira.axil.model.Vendedor;

@FacesConverter(forClass = Vendedor.class)
public class VendedorConverter implements Converter {

	@SuppressWarnings("unchecked")
	@Override
	public Vendedor getAsObject(FacesContext arg0, UIComponent componente, String valor) {
		HtmlSelectOneMenu menu = (HtmlSelectOneMenu) componente;
		UISelectItems itens = (UISelectItems) menu.getChildren().get(1);
		List<Vendedor> vendedores = (List<Vendedor>) itens.getValue();
		
		for (Vendedor vendedor : vendedores) {
			if(vendedor.getId().equals(new Long(valor)))
				return vendedor;
		}
		
		return null;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		return ((Vendedor)arg2).getId().toString();
	}

}
